﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace YemekteyizLib.Bs
{
    public class IlceProvider
    {
        /// <summary>
        /// Adam ilini seçmiş, ilçeleri göreceği zaman kullanılır
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static List<Ilce> getByIl(Il i)
        {
            SqlCommand cmd = new SqlCommand("select * from Ilceler where IlID = @ID");
            cmd.Parameters.AddWithValue("@ID", i.ID);
            cmd.Connection = Tools.GetConnection();
            List<Ilce> donecek = new List<Ilce>();
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                Ilce c = new Ilce();
                c.ID = rdr.GetInt32(0);
                c.Adi = rdr.GetString(1);
                c.Ili = i;
                donecek.Add(c);
            }            
            
            Tools.CloseConnection();

            return donecek;
            
        }

        public static Ilce GetByID(int id)
        {
            SqlCommand cmd = new SqlCommand("select * from Ilceler where IlCeID = @ID");
            cmd.Parameters.AddWithValue("@ID", id);
            cmd.Connection = Tools.GetConnection();
            int ilID = 0;
            SqlDataReader rdr = cmd.ExecuteReader();
            rdr.Read();
            Ilce c = new Ilce();
            c.ID = rdr.GetInt32(0);
            c.Adi = rdr.GetString(1);
            ilID = rdr.GetInt32(2);
            Tools.CloseConnection();

            c.Ili = IlProvider.getByID(ilID);

            return c;
        }

        public static void KaydetIlce(Ilce ilce)
        {

            SqlCommand cmd = new SqlCommand("update Ilceler set Adi=@p1,IlID=@p2 where IlceID=@ID");
            cmd.Parameters.AddWithValue("@p1", ilce.Adi);
            
            cmd.Parameters.AddWithValue("@p2", ilce.Ili.ID);
            cmd.Parameters.AddWithValue("@ID", ilce.ID);

            cmd.Connection = Tools.GetConnection();

            cmd.ExecuteNonQuery();

            Tools.CloseConnection();

        }
    }
}
